//
//  HomeViewController.m
//  KuWeiPark
//
//  Created by Kevin Su on 15/4/28.
//  Copyright (c) 2015年 Clief. All rights reserved.
//

#import "HomeViewController.h"
#import "PersonalInfoViewController.h"
#import "HttpClientManager.h"
#import "SettingViewController.h"
#import "MySaleTicketController.h"
#import "ShareViewController.h"
#import "MyMessageViewController.h"
#import "MyOrderViewController.h"
#import "MyWalletViewController.h"
#import "APIKey.h"
#import "ParkAnnotationView.h"
#import "ParkCallOutView.h"
#import "MyMAPointAnnotation.h"
#import "BookParkSpaceController.h"
#import "AppDelegate.h"
#import "AppMacro.h"
#import "SVProgressHUD.h"
#import "MyInfosViewController.h"
#import "TMCache.h"
#import "BookOrderDetailViewController.h"

@interface HomeViewController ()<MAMapViewDelegate, AMapNaviViewControllerDelegate, AMapNaviManagerDelegate, IFlySpeechSynthesizerDelegate, AMapSearchDelegate, HomeRecentOrderViewDelegate>

@end

@implementation HomeViewController{
    
    PersonalInfoViewController *personalInfoViewController;
    SettingViewController *settingViewController;
    MySaleTicketController *mySaleTicketController;
    ShareViewController *shareViewController;
    MyMessageViewController *myMessageViewController;
    MyOrderViewController *myOrderViewController;
    BookParkSpaceController *bookParkSpaceController;
    MyInfosViewController *myInfosViewController;
    MyWalletViewController *myWalletViewController;
    ParkCallOutView *currentParkCallOutView;
    
    NSMutableArray *locationArray;
    NSMutableArray *annotationsArray;
    
    LocationModel *locationModel;
    MAUserLocation *userCurrentLocation;
    LoginModel *loginModel;
    
    BOOL hasInvertGeo;
    
    MACoordinateRegion region; //默认显示地图区域
    
    HomeRecentOrderView *homeRecentOrderView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(execute:) name:Notify_ShowSelectedViewController object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPersonalInfoViewAction:) name:Notify_ShowPersonalInfoView object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(guideToParkPortWithNotification:) name:Notify_ShowGuideToParkPort object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bookParkingPortWithNotification:) name:Notify_ShowBookParkingPort object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutReturnMapview:) name:Notify_LogoutNotify object:nil];
    
    self.locateBtn.selected = NO;
    
    loginModel = ApplicationDelegate.loginModel;
    locationModel = ApplicationDelegate.locationModel;
    [self.navTitleBtn setTitle:locationModel.city forState:UIControlStateNormal];
    
    [MAMapServices sharedServices].apiKey = APIKey;
    hasInvertGeo = NO; //默认没有逆地址解析过
    
    [self initGaoDeMap];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [self initHomeOrderView];
}

- (void)initHomeOrderView{
    
    //初始化 首页订单信息
    if(homeRecentOrderView == nil){
        
        homeRecentOrderView = [[[NSBundle mainBundle] loadNibNamed:@"HomeRecentOrderView" owner:self options:nil] lastObject];
    }
    homeRecentOrderView.frame = CGRectMake(0, 0, self.view.frame.size.width, 0);
    homeRecentOrderView.delegate = self;
    [self.view addSubview:homeRecentOrderView];
    
    NSArray *orderArray = (NSArray *)[[TMDiskCache sharedCache] objectForKey:@"Orders"];
    if(orderArray.count != 0){
        
        BookParkingPortOrderModel *orderModel = orderArray[0];
        [homeRecentOrderView initDataWithOrderModel:orderModel];
        [UIView animateWithDuration:0.3 animations:^{
            
            homeRecentOrderView.frame = CGRectMake(0, 0, self.view.frame.size.width, 72);
        } completion:^(BOOL finished) {
            
            
        }];
    }
}

- (void)returnMapView{
    
    self.mapView.showsUserLocation = NO;
    self.mapView.delegate = nil;
    self.mapView = nil;
}

- (void)initGaoDeMap{
    
    //初始化高德地图
    
    //配置用户 Key
    if (self.mapView == nil)
    {
        self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    }
    
    [self.mapView setDelegate:self];
    [self.mapView setFrame:self.view.bounds];
    
    //先关闭 再显示 用户 定位图层
    self.mapView.showsUserLocation = NO;
    self.mapView.showsUserLocation = YES;
    
    //关闭 UserLocation 圆圈的定位图层  - 在 viewForOverlay 代理里执行
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView addAnnotations:annotationsArray];
    [self.view insertSubview:self.mapView atIndex:0];
}

- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay{
    
    //不加载 用户所在半径
    return nil;
}

- (void)invertGeoWithLa:(double)la Lo:(double)lo{
    
    //逆地址解析
    if(!hasInvertGeo){
        
        self.search = [[AMapSearchAPI alloc] initWithSearchKey:APIKey Delegate:self];
        
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        regeo.location = [AMapGeoPoint locationWithLatitude:la longitude:lo];
        regeo.requireExtension = YES;
        [self.search AMapReGoecodeSearch:regeo];
    }
}

#pragma mark - MAMapViewDelegate
#pragma mark - 定位
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    
    if(updatingLocation) {
        
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude, userLocation.coordinate.longitude);
        userCurrentLocation = userLocation;
        locationModel = [[LocationModel alloc] init];
        locationModel.la  = userLocation.coordinate.latitude;
        locationModel.lo = userLocation.coordinate.longitude;
        ApplicationDelegate.locationModel = locationModel;
        
        self.locateBtn.selected = YES;
        
        //逆地址解析
        [self invertGeoWithLa:userLocation.coordinate.latitude Lo:userLocation.coordinate.longitude];
    }
}

- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [SVProgressHUD showErrorWithStatus:@"获取地理位置信息失败"];
    });
}

#pragma mark - AMapSearchDelegate

/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        
        AMapAddressComponent *address = response.regeocode.addressComponent;
        NSString *cityName = address.city.length == 0? address.province : address.city;
        NSString *cityCode = response.regeocode.addressComponent.citycode;
        if([cityName containsString:@"市"]){
            
            locationModel.city = [cityName substringWithRange:NSMakeRange(0, cityName.length - 1)];
        }else{
            
            locationModel.city = cityName;
        }
        
        //当本地存储的 城市信息 有更换时, 更新本地存储, 并 重新刷新首页
        if(![locationModel.cityCode isEqualToString:cityCode]){
            
            locationModel.cityCode = cityCode;
            ApplicationDelegate.locationModel = locationModel;
            [[NSUserDefaults standardUserDefaults] setObject:[locationModel toDictionary] forKey:NsUserDefaultKey_LocationModel];
            hasInvertGeo = YES;
            
            //Update Navigation Title
            [self.navTitleBtn setTitle:locationModel.city forState:UIControlStateNormal];
            
            [self requestNearByParking];
        }
    }
}

#pragma mark - 地图加标注
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MyMAPointAnnotation class]])
    {
        MyMAPointAnnotation *myAnnotation = (MyMAPointAnnotation *)annotation;
        
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        
//===========  先关闭复用机制
//        ParkAnnotationView *annotationView = (ParkAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
//===========
        
        ParkAnnotationView *annotationView;
        if (annotationView == nil)
        {
            annotationView = [[ParkAnnotationView alloc] initWithAnnotation:annotation                                                             reuseIdentifier:pointReuseIndetifier];
            annotationView.mapView = self.mapView;
        }
        
        //赋值
        [annotationView initWithParkingModel:myAnnotation.parkingSearchModel];
        
        annotationView.draggable = YES;
        annotationView.canShowCallout = NO;
        annotationView.image = [UIImage imageNamed:@"clear_color_annotation"];
        annotationView.centerOffset = CGPointMake(0, -18);
        return annotationView;
    }
    
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 初始化讯飞语音
- (void)initIFlySpeech
{
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"55470730"];
    [IFlySpeechUtility createUtility:initString];
    if(self.iFlySpeechSynthesizer == nil){
        
        _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
        _iFlySpeechSynthesizer.delegate = self;
    }
}

#pragma mark - AMapNaviManager Delegate
- (void)AMapNaviManager:(AMapNaviManager *)naviManager didPresentNaviViewController:(UIViewController *)naviViewController
{
    
    [self.naviManager startEmulatorNavi];
}

- (void)AMapNaviManagerOnCalculateRouteSuccess:(AMapNaviManager *)naviManager
{
    // 初始化语音引擎
    [self initIFlySpeech];
    
    [self.naviManager presentNaviViewController:self.naviViewController animated:YES];
}

- (void)AMapNaviManager:(AMapNaviManager *)naviManager onCalculateRouteFailure:(NSError *)error
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"酷位停车提示" message:@"导航计算失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

#pragma mark - AManNaviViewController Delegate
- (void)AMapNaviViewControllerCloseButtonClicked:(AMapNaviViewController *)naviViewController
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.iFlySpeechSynthesizer stopSpeaking];
        self.iFlySpeechSynthesizer.delegate = nil;
        self.iFlySpeechSynthesizer = nil;
        [self.naviManager stopNavi];
        [self.naviManager dismissNaviViewControllerAnimated:YES];
        
        //当用户点击关闭时, 初始化 高德地图
        [self initGaoDeMap];
        [self locateAction:nil];
    });
}

- (void)AMapNaviViewControllerMoreButtonClicked:(AMapNaviViewController *)naviViewController
{
    if (self.naviViewController.viewShowMode == AMapNaviViewShowModeCarNorthDirection)
    {
        self.naviViewController.viewShowMode = AMapNaviViewShowModeMapNorthDirection;
    }
    else
    {
        self.naviViewController.viewShowMode = AMapNaviViewShowModeCarNorthDirection;
    }
}

- (void)AMapNaviViewControllerTrunIndicatorViewTapped:(AMapNaviViewController *)naviViewController
{
    [self.naviManager readNaviInfoManual];
}

- (void)AMapNaviManager:(AMapNaviManager *)naviManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType
{
    NSLog(@"playNaviSoundString:{%d:%@}", soundStringType, soundString);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        
        [_iFlySpeechSynthesizer startSpeaking:soundString];
        NSLog(@"start speak");
    });
}

#pragma mark - iFlySpeechDelegate
- (void)onCompleted:(IFlySpeechError*) error
{
    NSLog(@"Speak Error:{%d:%@}", error.errorCode, error.errorDesc);
}

#pragma mark - IBAction
- (IBAction)showPersonalInfoViewAction:(id)sender {
    
    personalInfoViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"PersonalInfoViewController"];
    [self.view.window addSubview:personalInfoViewController.view];
}

- (IBAction)locateAction:(id)sender {

    self.mapView.showsUserLocation = NO;
    self.mapView.showsUserLocation = YES;
    
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(locationModel.la, locationModel.lo) animated:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if(locationArray.count != 0){
            
            [self.mapView regionThatFits:region];
            [self.mapView setRegion:region animated:YES];
        }else{
            
            self.mapView.zoomLevel = 15;
        }
        
    });
}

#pragma mark - 收到通知执行跳转
- (void)execute:(NSNotification *)notification{
    
    NSDictionary *userinfo = notification.userInfo;
    int index = [userinfo[@"index"] intValue];
    switch (index) {
        case 0:
        {
            //个人资料
            myInfosViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MyInfosViewController"];
            myInfosViewController.loginModel = loginModel;
            [self.navigationController pushViewController:myInfosViewController animated:YES];
            break;
        }
        case 1:
        {
            //我的钱包
            myWalletViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MyWalletViewController"];
            [self.navigationController pushViewController:myWalletViewController animated:YES];
            break;
        }
        case 2:
        {
            
            //我的消息
            myMessageViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MyMessageViewController"];
            [self.navigationController pushViewController:myMessageViewController animated:YES];
            break;
        }
        case 3:
        {
            //我的订单
            myOrderViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MyOrderViewController"];
            [self.navigationController pushViewController:myOrderViewController animated:YES];
            break;
        }
        case 4:
        {
            
            //优惠券
            mySaleTicketController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MySaleTicketController"];
            [self.navigationController pushViewController:mySaleTicketController animated:YES];
            break;
        }
        case 5:
        {
            //分享
            shareViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ShareViewController"];
            [self.navigationController pushViewController:shareViewController animated:YES];
            break;
        }
        case 6:
        {
            
            //设置
            settingViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SettingViewController"];
            [self.navigationController pushViewController:settingViewController animated:YES];
            break;
        }
        default:
            break;
    }
}

#pragma mark - Notify_GuideToParkPort
- (void)guideToParkPortWithNotification:(NSNotification *)notification{
    
    NSDictionary *userinfo = notification.userInfo;
    id parkAnnotationView = userinfo[@"ParkAnnotationView"];
    [self guideWithAnnotationView:parkAnnotationView];
}

- (void)guideWithAnnotationView:(ParkAnnotationView *)parkAnnotationView{
    
    //导航
    [AMapNaviServices sharedServices].apiKey = APIKey;
    if(self.naviViewController == nil ){
        
        self.naviViewController = [[AMapNaviViewController alloc] initWithMapView:self.mapView delegate:self];
    }
    
    self.startPoint = [AMapNaviPoint locationWithLatitude:ApplicationDelegate.locationModel.la longitude:ApplicationDelegate.locationModel.lo];
    self.endPoint   = [AMapNaviPoint locationWithLatitude:[parkAnnotationView.parkingSearchModel.gpsLat doubleValue] longitude:[parkAnnotationView.parkingSearchModel.gpsLon doubleValue]];
    NSArray *startPoints = @[self.startPoint];
    NSArray *endPoints   = @[self.endPoint];
    
    if (self.naviManager == nil)
    {
        _naviManager = [[AMapNaviManager alloc] init];
        [_naviManager setDelegate:self];
    }
    [self.naviManager calculateDriveRouteWithStartPoints:startPoints endPoints:endPoints wayPoints:nil drivingStrategy:0];
}

#pragma mark - ShowBookParkingPlcaceNotification
- (void)bookParkingPortWithNotification:(NSNotification *)notification{
    
    NSDictionary *userinfo = notification.userInfo;
    id parkAnnotationView = userinfo[@"ParkAnnotationView"];
    [self bookParkPlaceWithAnnotationView:parkAnnotationView];
}

- (void)bookParkPlaceWithAnnotationView:(id)parkAnnotationView{
    
    //预订车位
    bookParkSpaceController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"BookParkSpaceController"];
    bookParkSpaceController.parkAnnotationView = parkAnnotationView;
    [self.navigationController pushViewController:bookParkSpaceController animated:YES];
}

#pragma mark - 用户退出后 回收 MapView资源
- (void)logoutReturnMapview:(NSNotification *)notification{
    
    [self returnMapView];
}

#pragma mark - 获取附近的停车场
- (void)requestNearByParking{
    
    [SVProgressHUD showWithStatus:@"正在获取周边停车场\n请等待..." maskType:SVProgressHUDMaskTypeClear];
    [[HttpClientManager sharedClient] mapParkingSearchRequestWithCityNo:locationModel.cityCode WithUserId:loginModel.userId Withgpslat:[NSString stringWithFormat:@"%f", locationModel.la] Withgpslon:[NSString stringWithFormat:@"%f", locationModel.lo] WithSucessBlock:^(JsonRetMsg *response) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
        });
        
        locationArray = response.data;
        annotationsArray = [[NSMutableArray alloc] init];
        for(ParkingSearchModel *parkingModel in locationArray){
            
            MyMAPointAnnotation *annotation = [[MyMAPointAnnotation alloc] init];
            annotation.coordinate = CLLocationCoordinate2DMake([parkingModel.gpsLat doubleValue], [parkingModel.gpsLon doubleValue]);
            annotation.parkingSearchModel = parkingModel;
            [annotationsArray addObject:annotation];
        }
        
        if(locationArray.count != 0){
            
            [self countFitZoomLevel];
        }
        
        
        [self.mapView removeAnnotations:self.mapView.annotations];
        [self.mapView addAnnotations:annotationsArray];
        
        //先关闭 再显示 用户 定位图层
        self.mapView.showsUserLocation = NO;
        self.mapView.showsUserLocation = YES;
        
    } withFailedBlock:^(JsonRetMsg *responseObject) {
        
    }];
}

//计算 适宜的 比例尺  使 所有的点显示在一屏以内
- (void)countFitZoomLevel{
    
    double maxDistance = 0;
    ParkingSearchModel *parkingModel;
    
    double center_la = locationModel.la;
    double center_lo = locationModel.lo;
    
    for (ParkingSearchModel *model in locationArray) {
        
        double latitude = [model.gpsLat doubleValue];
        double longitude = [model.gpsLon doubleValue];
        
        //1.将两个经纬度点转成投影点
        MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(latitude,longitude));
        MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(center_la,center_lo));
        
        //2.计算距离
        CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2);
        
        if(distance > maxDistance){
            
            maxDistance = distance;
            parkingModel = model;
        }
    }
    
    region.center.latitude = center_la;
    region.center.longitude = center_lo;
    region.span.latitudeDelta = (MAX([parkingModel.gpsLat doubleValue], center_la) - MIN([parkingModel.gpsLat doubleValue], center_la)) * 2.15;
    region.span.longitudeDelta = (MAX([parkingModel.gpsLon doubleValue], center_lo) - MIN([parkingModel.gpsLon doubleValue], center_lo)) * 2.15;
    
    //设置缩放等级
    [self.mapView regionThatFits:region];
    [self.mapView setRegion:region animated:YES];
    
}

#pragma mark - HomeRecentOrderViewDelegate

- (void)guideToDestinationWithOrderModel:(BookParkingPortOrderModel *)orderModel{
    
    ParkingSearchModel *model = [[ParkingSearchModel alloc] init];
    model.gpsLat = @"31.273025";
    model.gpsLon = @"121.431199";
    ParkAnnotationView *parkAnnotationView = [[ParkAnnotationView alloc] init];
    parkAnnotationView.parkingSearchModel = model;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:Notify_ShowGuideToParkPort object:nil userInfo:@{@"ParkAnnotationView": parkAnnotationView}];
}

- (void)showOrderDetailViewWithOrderModel:(BookParkingPortOrderModel *)orderModel{
    
    BookOrderDetailViewController *detailController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"BookOrderDetailViewController"];
    detailController.orderNo = orderModel.orderNo;
    [self.navigationController pushViewController:detailController animated:YES];
}

@end
